package com.pvdnc.tapkit.chat;

import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;

public class ManagedReference<T> {
    private final AtomicBoolean mReadable=new AtomicBoolean(true);
    private final AtomicBoolean mWritable=new AtomicBoolean(true);

    private final AtomicReference<T> mRef=new AtomicReference<>();

    public void setRef(T ref) throws IllegalStateException{
        synchronized (this) {
            if (!mWritable.get())
                throw new IllegalStateException("ref cannot be written now");
            mRef.set(ref);
        }
    }

    public T getRef() throws IllegalStateException{
        synchronized (this){
            if(!mReadable.get())
                throw new IllegalStateException("ref cannnot be read now");
            return mRef.get();
        }
    }

    public void setReadable(boolean readable){
        synchronized (this){
            mReadable.set(readable);
        }
    }

    public boolean isReadable(){
        synchronized (this) {
            return mReadable.get();
        }
    }

    public void setWritable(boolean writable){
        synchronized (this){
            mWritable.set(writable);
        }
    }
}
